use loco_rs::prelude::*;
use sea_orm::DeleteResult;
use serde::{Deserialize, Serialize};
use uuid::Uuid;

pub use super::_entities::order_shipments::{self, ActiveModel, Entity, Model};

#[derive(Debug, Deserialize, Serialize)]
pub struct CreateParams {
    pub order_id: String,
    pub express_code: String,
    pub express_company: String,
    pub express_number: String,
}

#[derive(Debug, Validate, Deserialize)]
pub struct Validator {
    #[validate(length(min = 1, message = "Order ID must not be empty."))]
    pub order_id: String,
    #[validate(length(min = 1, message = "Express Code must not be empty."))]
    pub express_code: String,
    #[validate(length(min = 1, message = "Express Company must not be empty."))]
    pub express_company: String,
    #[validate(length(min = 1, message = "Express Number must not be empty."))]
    pub express_number: String,
}

impl Validatable for ActiveModel {
    fn validator(&self) -> Box<dyn Validate> {
        Box::new(Validator {
            order_id: self.order_id.as_ref().to_owned(),
            express_code: self.express_code.as_ref().to_owned(),
            express_company: self.express_company.as_ref().to_owned(),
            express_number: self.express_number.as_ref().to_owned(),
        })
    }
}

#[async_trait::async_trait]
impl ActiveModelBehavior for super::_entities::order_shipments::ActiveModel {
    async fn before_save<C>(self, _db: &C, insert: bool) -> Result<Self, DbErr>
    where
        C: ConnectionTrait,
    {
        self.validate()?;
        if insert {
            let mut this = self;
            this.id = ActiveValue::Set(Uuid::new_v4().to_string());
            Ok(this)
        } else {
            Ok(self)
        }
    }
}

impl Model {
    /// finds an order shipment by the provided id
    ///
    /// # Errors
    ///
    /// When could not find order shipment or DB query error
    pub async fn find_by_id(db: &DatabaseConnection, id: &str) -> ModelResult<Self> {
        let order_shipment = order_shipments::Entity::find()
            .filter(
                model::query::condition()
                    .eq(order_shipments::Column::Id, id)
                    .build(),
            )
            .one(db)
            .await?;
        order_shipment.ok_or_else(|| ModelError::EntityNotFound)
    }

    /// finds order shipments by the provided order id
    ///
    /// # Errors
    ///
    /// When could not find order shipments or DB query error
    pub async fn find_by_order_id(
        db: &DatabaseConnection,
        order_id: &str,
    ) -> ModelResult<Vec<Self>> {
        let order_shipments = order_shipments::Entity::find()
            .filter(
                model::query::condition()
                    .eq(order_shipments::Column::OrderId, order_id)
                    .build(),
            )
            .all(db)
            .await?;
        Ok(order_shipments)
    }

    /// Asynchronously creates an order shipment and saves it to the database.
    ///
    /// # Errors
    ///
    /// When could not save the order shipment into the DB
    pub async fn create(db: &DatabaseConnection, params: &CreateParams) -> ModelResult<Self> {
        let order_shipment = order_shipments::ActiveModel {
            order_id: ActiveValue::set(params.order_id.to_string()),
            express_code: ActiveValue::set(params.express_code.to_string()),
            express_company: ActiveValue::set(params.express_company.to_string()),
            express_number: ActiveValue::set(params.express_number.to_string()),
            ..Default::default()
        }
        .insert(db)
        .await?;

        Ok(order_shipment)
    }

    /// Deletes the order shipment
    ///
    /// # Errors
    ///
    /// When could not delete the order shipment from the DB
    pub async fn delete(self, db: &DatabaseConnection) -> ModelResult<DeleteResult> {
        let model: order_shipments::ActiveModel = self.into();
        Ok(model.delete(db).await?)
    }
}

impl ActiveModel {
    /// Updates the order shipment's express information
    ///
    /// # Errors
    ///
    /// when has DB query error
    pub async fn update_express_info(
        mut self,
        db: &DatabaseConnection,
        express_code: String,
        express_company: String,
        express_number: String,
    ) -> ModelResult<Model> {
        self.express_code = ActiveValue::set(express_code);
        self.express_company = ActiveValue::set(express_company);
        self.express_number = ActiveValue::set(express_number);
        Ok(self.update(db).await?)
    }
}
